﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;

namespace proxyTest
{
    class ProxyTester
    {
        public ProxyTester()
        { }
        static public int TestProxy(string url, string proxy, int port)
        {
            DateTime t1 = new DateTime();
            DateTime t2 = new DateTime();
            try
            {
                if (!"".Equals(proxy))
                {
                    WebProxy proxyObject = new WebProxy(proxy, port);

                    // Disable proxy use when the host is local. 
                    proxyObject.BypassProxyOnLocal = true;

                    // HTTP requests use this proxy information. 
                    WebRequest.DefaultWebProxy = proxyObject;

                }
                Uri uri = new Uri(url);
                WebRequest req = WebRequest.Create(uri);
                t1 = DateTime.Now;
                WebResponse result = req.GetResponse();
                t2 = DateTime.Now;
                /*Stream ReceiveStream = result.GetResponseStream(); 
                Encoding encode = System.Text.Encoding.GetEncoding("utf-8"); 
                StreamReader sr = new StreamReader(ReceiveStream, encode); 
 
                // Read the stream into arrays of 30 characters 
                // to add as items in the list box. Repeat until 
                // buffer is read. 
                Char[] read = new Char[30]; 
                int count = sr.Read(read, 0, 30); 
                while (count > 0) 
                { 
                    String str = new String(read, 0, count); 
                    Console.WriteLine(str); 
                    count = sr.Read(read, 0, 30); 
                }*/
            }
            catch (WebException ex)
            {
                string message = ex.Message;
                HttpWebResponse response = (HttpWebResponse)ex.Response;
                if (null != response)
                {
                    message = response.StatusDescription;
                    response.Close();
                    t1 = t2;
                }
                Console.WriteLine("An Web Exception:" + message);
            }
            catch (Exception ex)
            {
                Console.WriteLine("An Exception" + ex.Message);
                t1 = t2;
            }
            //Console.WriteLine("t2=" + t2); 
            //Console.WriteLine("t1=" + t1); 
            //Console.WriteLine("t2-t1" + (t2 - t1)); 
            return t2.Second * 1000 + t2.Millisecond - t1.Second * 1000 - t1.Millisecond;
        }
    }

}